package com.ruoyi.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.api.annotation.Login;
import com.ruoyi.business.app.bo.AppWithdrawApplyQueryBo;
import com.ruoyi.business.app.bo.AppWithdrawDetailQueryBo;
import com.ruoyi.business.app.bo.HcxAppUserCardbankBo;
import com.ruoyi.business.app.service.IMyWalletService;
import com.ruoyi.business.app.vo.AppUserPriceBo;
import com.ruoyi.business.app.vo.CommonIdNameCountDTO;
import com.ruoyi.business.app.vo.WalletAccountDetailVo;
import com.ruoyi.business.app.vo.WalletWithdrawRecordVo;
import com.ruoyi.business.domain.HcxAppUser;
import com.ruoyi.business.domain.HcxAppUserCardbank;
import com.ruoyi.business.service.IHcxAppUserCardbankService;
import com.ruoyi.business.service.IHcxAppUserService;
import com.ruoyi.business.service.IHcxWithdrawApplyService;
import com.ruoyi.business.service.IHcxWithdrawDetailService;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.AssertUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Api(tags = "我的钱包")
@RestController
@RequestMapping("/api/wallet")
@AllArgsConstructor
public class MyWalletController extends BaseController {

    private final IMyWalletService iMyWalletService;


    private final IHcxAppUserService appUserService;


    private final IHcxWithdrawDetailService withdrawDetailService;


    private final IHcxAppUserCardbankService appUserCardbankService;

    private final IHcxWithdrawApplyService applyService;

    private final ISysConfigService configService;


    private final ISysDictDataService dictDataService;

    @Login
    @ApiOperation("查询余额、农产品奖、推广奖、门店收入奖")
    @GetMapping("/balance")
    public AjaxResult<AppUserPriceBo> myBalance() {
        AppUserPriceBo appUserPriceBo = appUserService.getVoOne(new LambdaQueryWrapper<HcxAppUser>().eq(HcxAppUser::getId, SecurityUtils.getUserId()), AppUserPriceBo.class);
        return AjaxResult.success("success", appUserPriceBo);
    }

    @Login
    @ApiOperation("账单明细")
    @GetMapping("/account/detail")
    public TableDataInfo<WalletAccountDetailVo> accountDetail(AppWithdrawDetailQueryBo bo) {
        TableDataInfo<WalletAccountDetailVo> pages = withdrawDetailService.queryAppPageList(bo);
        List<WalletAccountDetailVo> rows = pages.getRows();
        for (WalletAccountDetailVo row : rows) {
            String amountStr = row.getAmount();
            // 0为余额提现  1位推广奖提现
            if (Constants.ZERO.equals(row.getDetailType()) || Constants.ONE.equals(row.getDetailType())) {
                amountStr = "-" + amountStr;
            } else {
                amountStr = "+" + amountStr;
            }
            row.setAmount(amountStr);
            SysDictData hcxDetailType = dictDataService.getOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, "hcx_detail_type").eq(SysDictData::getDictValue, row.getDetailType()));
            row.setDetailType(hcxDetailType.getDictLabel());
        }
        return pages;
    }

    @Login
    @ApiOperation("提现手续费比例")
    @GetMapping("/fee/proportion")
    public AjaxResult<BigDecimal> feeProportion() {

        LambdaQueryWrapper query = new LambdaQueryWrapper<SysConfig>()
                .select(SysConfig::getConfigValue).eq(SysConfig::getConfigKey, Constants.WITHDRAW_FEE_PROPORTION);
        BigDecimal feeProportion = new BigDecimal(0);
        SysConfig sysConfig = configService.getOne(query);
        if (sysConfig != null && StringUtils.isNumeric(sysConfig.getConfigValue())) {
            feeProportion = new BigDecimal(sysConfig.getConfigValue());
        }

        return AjaxResult.success("success", feeProportion);
    }

    @Login
    @ApiOperation("我绑定的银行卡列表")
    @GetMapping("/bankcard/list")
    public AjaxResult<List<CommonIdNameCountDTO>> bankCardList() {
        LambdaQueryWrapper query = new LambdaQueryWrapper<HcxAppUserCardbank>().
                select(HcxAppUserCardbank::getId, HcxAppUserCardbank::getBankName, HcxAppUserCardbank::getBankCardNo)
                .eq(HcxAppUserCardbank::getUserId, SecurityUtils.getUserId());
        List<HcxAppUserCardbank> list = appUserCardbankService.list(query);
        List<CommonIdNameCountDTO> vos = new ArrayList<>();
        for (HcxAppUserCardbank card : list) {
            CommonIdNameCountDTO dto = new CommonIdNameCountDTO();
            dto.setId(card.getId());
            dto.setName(card.getBankName());
            String cardNo = card.getBankCardNo();
            //替换后四位之前的字符为*
            if (StringUtils.isNotEmpty(cardNo) && cardNo.length() > 4) {
                String replaceStr = cardNo.substring(0, cardNo.length() - 4);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < (cardNo.length() - 4); i++) {
                    sb.append("*");
                }
                cardNo = cardNo.replace(replaceStr, sb.toString());
            }
            dto.setCode(cardNo);
            vos.add(dto);
        }
        return AjaxResult.success(vos);
    }

    @Login
    @RepeatSubmit
    @ApiOperation("删除银行卡")
    @GetMapping("/bankcard/delete")
    public AjaxResult bankCardDelete(@ApiParam("银行卡主键") @RequestParam Long id) {
        LambdaQueryWrapper queryCount = new LambdaQueryWrapper<HcxAppUserCardbank>().
                eq(HcxAppUserCardbank::getId, id).eq(HcxAppUserCardbank::getUserId, SecurityUtils.getUserId());
        AssertUtils.isTrue(appUserCardbankService.count(queryCount) > 0, "名下无此银行卡，请检查");
        appUserCardbankService.deleteWithValidByIds(Arrays.asList(id), false);
        return AjaxResult.success();
    }

    @Login
    @RepeatSubmit
    @ApiOperation(value = "提交提现申请", notes = "返回码：412-未设置支付密码，请先设置")
    @PostMapping("/withdraw/apply")
    public AjaxResult withdrawApply(@ApiParam("金额") @RequestParam BigDecimal amt,
                                    @ApiParam("提现类型(0 余额提现  1是推广奖提现  2 门店收入提现)") @RequestParam String type,
                                    @ApiParam("提现方式(0 支付宝 1 微信)") @RequestParam String txType) {
        return iMyWalletService.apply(amt,type,txType);
    }

    @Login
    @ApiOperation("提现明细")
    @GetMapping("/withdraw/record")
    public TableDataInfo<WalletWithdrawRecordVo> withdrawRecord(AppWithdrawApplyQueryBo bo) {
        return applyService.queryAppPageList(bo);
    }

    @Login
    @ApiOperation("银行名称列表")
    @GetMapping("/bankname/list")
    public AjaxResult bankNameList() {
        List<SysDictData> sysBankNameList = DictUtils.getDictCache(Constants.BANK_LIST);
        List<String> bankNameList = sysBankNameList.stream().map(e -> e.getDictLabel()).collect(Collectors.toList());
        return AjaxResult.success(bankNameList);
    }

    @Login
    @RepeatSubmit
    @ApiOperation("绑定支付宝")
    @PostMapping("/bankcard/bind")
    public AjaxResult bankCardBind(@RequestBody HcxAppUserCardbankBo bo) {
        int i = iMyWalletService.bankCardBind(bo);
        return toAjax(i);
    }
}
